<?php

namespace app\ypz_forum_admin\controller;

use app\BaseController;
use think\Facade\Db;
use think\Facade\Session;

class Admin extends BaseController
{
    
    //登录页面 R2103010231
    public function alogin()
    {
        return view();
    }
    
    //登录逻辑 R2103010231
    public function aDoLogin()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        if (!$username) {
            $this->error('请输入用户名!');
        }
    
        if (!$password) {
            $this->error('请输入密码!');
        }
    
        $res = Db::name('admin_user')
            ->where('username', $username)
            ->find();
        
        if ($res) {
            if ($res['password'] == md5($password)) {
                //登录成功
                //dump($res);
                Session::set('user', $res);
                $this->success('登录成功!', '/ypz_forum_admin/deal/mesdeal');
            } else {
                $this->error('密码不正确!');
            }
        }
        $this->error('用户名不存在, 登录失败!');
    }
    
    //修改密码页面 R2103010231
    public function apa()
    {
        return view();
    }
    
    //修改密码逻辑 R2103010231
    public function aDoPa()
    {
        // 判断是否已经登录 R2103010231
        $this->check_login();
        $username = $this->request->post('username','','trim');
        $password = $this->request->post('password','','trim');
        $new_password_1 = $this->request->post('new_password_1','','trim');
        $new_password_2 = $this->request->post('new_password_2','','trim');
    
        if ($new_password_1 == $password) {
            $this->error('新旧密码一致!');
        }
        
        if ($new_password_1 != $new_password_2) {
            $this->error('密码不一致!');
        }
        
        // 修改密码 R2103010231
        $re = Db::name('admin_user')
            ->where('username', $username)
            ->where('password', md5($password))
            ->update(['password' =>  md5($new_password_1)]);
        // dump($re);
        if ($re == 1){
            #修改成功
            $this->success('修改成功，请重新登录!','admin/alogout');
        }else{
            #修改失败
            $this->error('旧密码不正确!');
        }
    }
    
    //注销 R2103010231
    public function aLogOut()
    {
        $this->check_login();
        // 清除变量
        Session::delete('user');
        Session::clear();
        // 跳转
        $this->success('注销成功!','admin/alogin');
    }
}
